package com.itheima.youdianda.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException sicve){
        String errMessage = sicve.getMessage();
        if (errMessage.contains("Duplicate entry")) {
            String[] err = errMessage.split(" ");
            return R.error(err[2]+"已存在");
        }
        return R.error("未知错误");
    }

    /**
     * 自定义异常处理方法(分类下有菜品关联无法删除)
     * @param ce
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException ce){
        log.info(ce.getMessage());
        return R.error(ce.getMessage());
    }
}
